package com.example.accessdemo.controller;

import cn.hutool.core.util.IdUtil;
import com.alibaba.excel.EasyExcel;
import com.example.accessdemo.aop.EnableAsync;
import com.example.accessdemo.dao.UploadDAO;
import com.example.accessdemo.dao.UploadData;
import com.example.accessdemo.domain.AsyncMsg;
import com.example.accessdemo.domain.Result;
import com.example.accessdemo.listener.UploadDataListener;
import com.example.accessdemo.service.AsyncService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @ClassName AsynImportDemoController
 * @Description 异步上传的demo示例，大数据量导入后，支持轮询查询该导入任务的实时进度：
 * step1：优先调用upload接口，上传Excel文件，
 * step2：上传成功后将返回的ID作为参数调用findAsyncMsg接口。轮询该任务的实时进度
 * @Author kuangdda
 * @Date 16:54 2023/1/9
 * @Version 1.0
 **/
@RestController
@RequestMapping("/demo")
public class AsynImportDemoController {

    @Resource
    private AsyncService asyncService;

    @Resource
    private UploadDAO uploadDAO;

    /**
     * @RequestPart
     * @RequestPart这个注解用在multipart/form-data表单提交请求的方法上。
     * 支持的请求方法的方式MultipartFile，属于Spring的MultipartResolver类。这个请求是通过http协议传输的
     * @RequestParam
     * @RequestParam支持’application/json’，也同样支持multipart/form-data请求
     * 区别
     * 当请求方法的请求参数类型不是String 或 MultipartFile / Part时，而是复杂的请求域时，
     * @RequestParam 依赖Converter or PropertyEditor进行数据解析，
     * RequestPart参考 ‘Content-Type’ header，依赖HttpMessageConverters 进行数据解析
     * @param file 上传的Excel文件
     * @return
     * @throws IOException
     */
    @EnableAsync
    @PostMapping("upload")
    public Result upload(@RequestPart(value = "file", required = false) MultipartFile file) throws IOException {
        String filename = file.getOriginalFilename();//获取文件的名称

        String flag = IdUtil.fastSimpleUUID();//通过Hutool工具包的IdUtil类获取uuid作为前缀
        String rootFilePath = System.getProperty("user.dir") + "/src/main/resources/files/" + flag + "_" + filename;


        File uploadFile = new File(rootFilePath);
        //先存储到磁盘
        if (!uploadFile.getParentFile().exists()) {
            uploadFile.getParentFile().mkdirs();
        }
        file.transferTo(uploadFile);

        EasyExcel.read(new FileInputStream(uploadFile), UploadData.class, new UploadDataListener(uploadDAO,asyncService)).sheet().doRead();

        return Result.success("执行完毕！");
    }

    /**
     * 根据异步线程任务ID查询任务运行状态和进度
     * @param id 任务ID
     * @return
     * @throws InterruptedException
     */
    @RequestMapping(value = "findAsyncMsg", method = RequestMethod.POST)
    public Result<AsyncMsg> findAsyncMsg(String id) throws InterruptedException {
        AsyncMsg asyncMsg = asyncService.findAsyncMsg(id);
        return Result.success(asyncMsg);
    }
}
